const mysql  = require('mysql')
const dbConfig = require('../../dbs/config')

const pool = mysql.createPool(dbConfig.DB.relationalConfs[0])

const db = {
  query: function (sql, values) {
    return new Promise((resolve, reject) => {
        // console.log('length1', pool._allConnections.length)
        pool.getConnection((err, conn) => {
            if (err) return reject(err)
            conn.query(sql, values, (err, rows) => {
                if (err) reject(err)
                else resolve(rows)
                // conn.release()
                // conn.release(); // not work!!!
                pool.releaseConnection(conn)
                // conn.destroy()
                // console.log('length2', pool._allConnections.length)
            })
        })
        // pool.getConnection(function(err,connection) {
        //       if(err) {
        //           console.log("建立连接失败");
        //       }else{
        //           console.log("建立连接成功");
        //           console.log(pool._allConnections.length);//1 
        //           connection.query(sql, function(err,rows) {
        //               if(err) {
        //                   console.log("查询失败");
        //               }else{
        //                   console.log(rows);               
        //               }
        //               // connection.destroy();
        //               console.log(pool._allConnections.length);//0    
        //           })
        //       }
        //       pool.end()
        // })
    })
  }
}

module.exports = db